﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using JinianNet.JNTemplate;

namespace JinianNet.Web.MVC
{
    public class TemplateView : IView
    {
        #region IView 成员
        private ITemplate templateManage = null;
        private string viewPath;

        public TemplateView(string path)
        {
            this.viewPath = path;
        }

        public TemplateView(ITemplate template)
        {
            this.templateManage = template;
        }

        public void Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
            string key = System.Web.HttpUtility.UrlEncode(viewContext.RequestContext.HttpContext.Request.Url.PathAndQuery);
            Cache.FileCache cache = new Cache.FileCache();
            object item = cache.Get(key);
            if (item == null)
            {
                if (templateManage == null)
                {
                    if (!string.IsNullOrEmpty(viewPath))
                    {
                        if (viewPath.StartsWith("~/"))
                        {
                            viewPath = viewContext.HttpContext.Server.MapPath(viewPath);
                        }

                        templateManage = JNTemplate.BuildManager.CreateTemplate(viewPath);
                    }
                }
                foreach (KeyValuePair<string, object> value in viewContext.ViewData)
                {
                    this.templateManage.Context.TempData[value.Key] = value.Value;
                }
                using (System.IO.StringWriter sw = new System.IO.StringWriter())
                {
                    templateManage.Render(sw);
                    item = sw.ToString();
#if !DEBUG
                    cache.Insert(key, item);
#endif
                }
            }
            writer.Write(item);
        }

        #endregion
    }
}
